{{#if (eq payments "polar")}}
import { Button } from "@/components/ui/button";
{{/if}}
import { authClient } from "@/lib/auth-client";
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
{{#if ( or (eq api "orpc") (eq api "trpc"))}}
import { useQuery } from "@tanstack/react-query";
{{/if}}
import { useEffect, useState } from "react";
import { useNavigate } from "react-router";

export default function Dashboard() {
  const { data: session, isPending } = authClient.useSession();
  const navigate = useNavigate();
  {{#if (eq payments "polar")}}
  const [customerState, setCustomerState] = useState<any>(null);
  {{/if}}

  {{#if (eq api "orpc")}}
  const privateData = useQuery(orpc.privateData.queryOptions());
  {{/if}}
  {{#if (eq api "trpc")}}
  const privateData = useQuery(trpc.privateData.queryOptions());
  {{/if}}

  useEffect(() => {
    if (!session && !isPending) {
      navigate("/login");
    }
  }, [session, isPending, navigate]);

  {{#if (eq payments "polar")}}
  useEffect(() => {
    async function fetchCustomerState() {
      if (session) {
        const { data } = await authClient.customer.state();
        setCustomerState(data);
      }
    }

    fetchCustomerState();
  }, [session]);
  {{/if}}

  if (isPending) {
    return <div>Loading...</div>;
  }

  {{#if (eq payments "polar")}}
  const hasProSubscription = customerState?.activeSubscriptions?.length! > 0;
  console.log("Active subscriptions:", customerState?.activeSubscriptions);
  {{/if}}

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome {session?.user.name}</p>
      {{#if ( or (eq api "orpc") (eq api "trpc"))}}
      <p>API: {privateData.data?.message}</p>
      {{/if}}
      {{#if (eq payments "polar")}}
      <p>Plan: {hasProSubscription ? "Pro" : "Free"}</p>
      {hasProSubscription ? (
        <Button onClick={async () => await authClient.customer.portal()}>
          Manage Subscription
        </Button>
      ) : (
        <Button onClick={async () => await authClient.checkout({ slug: "pro" })}>
          Upgrade to Pro
        </Button>
      )}
      {{/if}}
    </div>
  );
}
